package com.comp3111.happymeal;


import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.configuration.Configuration;
import com.configuration.Owner;
import com.controller.*;
import com.object.*;
import com.user.Helper;

import android.view.*;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;

public class FoodPageActivity extends NavigationDrawerActivity {

	private ListView listView;
    private SimpleAdapter adapter;
    
    //holding the meal id
    int mealId;
    
    //Constant for displaying listview
    final int NUM_COMMENT = 5;
    
    //Class attribute for loading pictures
    Drawable mealPicture;
    Drawable userProfilePicture;
    String userProfilePictureDrawableURL;
    
    //For handling the onclick user comment
    private List<Integer> commentUserIdList;
    private List<Integer> commentIdList;
    
    //Selected meal comment id
    int selectedMealComment;
    
    @SuppressLint("NewApi")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Bundle extras = getIntent().getExtras();
		
        setContentView(R.layout.food_page);
        createDrawer();
        
        Button commentBtn = (Button) findViewById(R.id.food_page_comment);
        commentBtn.setOnClickListener(new OnClickListener() {
        	@Override
            public void onClick(View v) {
            	createDialog();
            }
        });
        
        selectedMealComment = -1;
        
        mealId = Integer.parseInt(extras.getString("MEALID"));	//Check out discoverPageActivity onClickListener
		
		//Fetch the meal of id
		MealFetch mealFetch = new MealFetch();
		Meal meal = mealFetch.fetchMealById(mealId);
		
		//link the textview to xml
		TextView tv_food_page_restaurant_name = (TextView)findViewById(R.id.food_page_restaurant_name);
		TextView tv_food_page_name = (TextView)findViewById(R.id.food_page_name);
		TextView tv_food_page_restaurant_price = (TextView)findViewById(R.id.food_page_restaurant_price);
		TextView tv_food_page_like = (TextView)findViewById(R.id.food_page_like);
		TextView tv_food_page_tag = (TextView)findViewById(R.id.food_page_tag);
		TextView tv_food_page_description = (TextView)findViewById(R.id.food_page_description);
		ImageView iv_food_page_love = (ImageView)findViewById(R.id.food_page_love);
		
		//Get the variable of imageview
		View iv_food_page_picture = (View)findViewById(R.id.food_page_picture);
		iv_food_page_picture.setTag(Configuration.baseURL + meal.getPicture());
		new DownloadImagesTask().execute(iv_food_page_picture);
		
		MealCommentFetch mealCommentFetch = new MealCommentFetch();
		//Test if the owner has loves the food or not
		if(mealCommentFetch.isLikedByUser(meal.getId(),Owner.id)){
			//Like by user
			iv_food_page_love.setImageResource(R.drawable.love);
		}else{
			//Not yet like by user
			iv_food_page_love.setImageResource(R.drawable.nolove);
		}
		
		final int mealIdTmp = meal.getId();
		
		//Imageview onClickListener
		iv_food_page_love.setOnClickListener(new View.OnClickListener() {
		    @Override
		    public void onClick(View v) {
		    	MealCommentFetch mealCommentFetchTmp = new MealCommentFetch();
		    	MealCommentUpdate mealCommentUpdateTmp = new MealCommentUpdate();
		    	
		    	
		    	if(mealCommentFetchTmp.isLikedByUser(mealIdTmp,Owner.id)){
		    		//Already liked by user
		    		//Press to unlike
		    		mealCommentUpdateTmp.unlikeMeal(mealIdTmp);
		    	}else{
		    		//Not liked by user
		    		//Press to like
		    		mealCommentUpdateTmp.likeMeal(mealIdTmp);
		    	}
		    	
		    	//Refresh page after clicking
		    	Intent intent = getIntent();
                finish();
                startActivity(intent);
		    }
		});
		
		//Set Text for the textview
		RestaurantFetch restaurantFetch = new RestaurantFetch();
		String restaurantName = restaurantFetch.fetchRestaurantNameById(meal.getRestaurant());
		
		tv_food_page_restaurant_name.setText(restaurantName);
		tv_food_page_name.setText(meal.getName());
		tv_food_page_restaurant_price.setText("$" + meal.getPrice());
		
		int numberOfLike = mealFetch.fetchMealLikeById(meal.getId());
		tv_food_page_like.setText(Integer.toString(numberOfLike) + " love(s)");
		//Tag part will be re-written
		String tagString = "";
		for(int i = 0; i < Configuration.tagNumber; i++) {
				tagString = tagString + " #" + meal.getTagByIndex(i) + "\n";
		}
		tv_food_page_tag.setText(tagString);
		tv_food_page_description.setText(meal.getDescription());
		
        
        listView = (ListView)findViewById(R.id.listView);
        adapter = new SimpleAdapter(this, getMealComment(), R.layout.food_user_review,
				new String[]{"user_review_pic","name", "comments","time", "love_pic"},
				new int[]{R.id.user_review_pic, R.id.food_review_user_name, R.id.food_review_comments, R.id.food_review_time, R.id.food_review_love_pic});
        listView.setAdapter(adapter);
        
        //For displaying picture
        adapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	
            	int userId = commentUserIdList.get(position);
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(FoodPageActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);

            }
        });  
        
        /*
         * Alert dialog for deletion of comment
         */
        AlertDialog.Builder builder1 = new AlertDialog.Builder(FoodPageActivity.this);
        builder1.setMessage("Do you want to remove your comment?");
        builder1.setCancelable(true);
        builder1.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	/*
            	 * TODO : Remove that comment from the server
            	 */
            	if(selectedMealComment != -1){
	        		MealCommentUpdate mealCommentUpdate = new MealCommentUpdate();
	        		mealCommentUpdate.removeMealComment(selectedMealComment);
	            	
	        		//Reset the selectedMealComment
	        		selectedMealComment = -1;
	        		
	        		// TODO : Refresh activity
	        		Intent intent = getIntent();
	                finish();
	                startActivity(intent);

	                dialog.cancel();
            	}
            }
        });
        builder1.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	
            	//Reset the selectedMealComment
        		selectedMealComment = -1;
            	
        		dialog.cancel();
            }
        });

        final AlertDialog alert11 = builder1.create();
        
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
            	int userId = commentUserIdList.get(position);
            	if(userId == Owner.id){
            		// TODO : Implement pop up ask if delete of message
            		selectedMealComment = commentIdList.get(position);
            		alert11.show();
            	}
            	return false;
            }
        }); 
        /*
        listView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
            	if(event.getAction()!= MotionEvent.ACTION_UP){
            		return false;
            	}
            	
            	int itemNum = listView.getCount();
                
                if(itemNum == 0){
                	return false;
                }
                
                //Transform the y to position
            	float y = (int) event.getY();
                float itemHeight = listView.getHeight()/itemNum;
                int position = -1;
                
                for(int i=0;i<NUM_COMMENT;i++){
                	float lower = i*itemHeight;
                	float upper = lower + itemHeight;
                	if(y>lower && y<upper){
                		position = i;
                	}
                }
                
                if(position>NUM_COMMENT-1 || position<0){
                	return false;
                }
                
            	int userId = commentUserIdList.get(position);
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(FoodPageActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);
                // Disallow the touch request for parent scroll on touch of
                // child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        */
        Helper.setListViewHeightBasedOnChildren(listView);
        
        //Release unused ram
        System.gc();
    }
    
    
    protected void createDialog() {
    	LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.food_page_comment_dialog, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setView(textEntryView)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
                	/*upload comment*/
                	MealCommentUpdate mealCommentUpdate = new MealCommentUpdate();
                	
                	//Get text from edit text
                	EditText et_food_page_comment_dialog_comment = (EditText) textEntryView.findViewById(R.id.food_page_comment_dialog_comment);
                	String comment = et_food_page_comment_dialog_comment.getText().toString();
                	
                	//Do not allow posting empty comment
                	if(comment.isEmpty()){
                		Toast.makeText(getApplicationContext(), "Post Cancel",Toast.LENGTH_SHORT).show();
                		return;
                	}
                	
                	//Check if posting of comment is successful
                	int SUCCESS = 1;
                	if(SUCCESS == mealCommentUpdate.uploadMealComment(Owner.id, mealId,comment)){
                		Toast.makeText(getApplicationContext(), "Comment Posted",Toast.LENGTH_SHORT).show();
                	}else{
                		Toast.makeText(getApplicationContext(), "Fail to post comment, please try again",Toast.LENGTH_LONG).show();
                	}
                	
                	//Reload the list view in user review
                	Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                }
            })
            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked cancel so do some stuff */
                }
            });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    
    
    private List<Map<String, Object>> getMealComment() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		commentUserIdList = new ArrayList<Integer>();
		commentIdList = new ArrayList<Integer>();
		
		MealCommentFetch mealCommentFetch = new MealCommentFetch();
		List<MealComment> mealCommentList = mealCommentFetch.fetchMealCommentByMealId(mealId);
		UserFetch userFetch = new UserFetch();
		
		if(mealCommentList != null){
			int counter = 0;
		    for(MealComment mealComment : mealCommentList){
		    	// Display at most 5 comments
		    	if(counter > NUM_COMMENT-1){
		    		break;
		    	}else{
		    		counter++;
		    	}
							
				//drawableURL = Configuration.baseURL + restaurant.getProfilePicture();
				Map<String, Object> map = new HashMap<String, Object>();
				
				User user = userFetch.fetchUserById(mealComment.getUser());
				
				if(user.getProfilePicture()!=null){
					
					userProfilePictureDrawableURL = Configuration.baseURL + user.getProfilePicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  						
							userProfilePicture = loadImageFromURL(userProfilePictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				map.put("user_review_pic",userProfilePicture);
				map.put("name", userFetch.fetchUserNameById(mealComment.getUser()));
				map.put("comments", mealComment.getComment());
				map.put("time", mealComment.getCreateDate());
				
				if(mealCommentFetch.isLikedByUser(mealId,user.getId())){
					map.put("love_pic", R.drawable.love);
				}else{
					map.put("love_pic", R.drawable.nolove);
				}
				
				list.add(map);
				
				//List containing restaurant id in order
				commentUserIdList.add(mealComment.getUser());
				commentIdList.add(mealComment.getId());
	    	}
		    
		    
	    }else{
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("comments","No comments yet!");
	    	list.add(map);
	    }

		return list;
	}
    
    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
            /*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;
            */
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
}